import axios, {
  AxiosError,
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
} from 'axios';

import { Axios } from '@/interface/index';

const config = {
  // baseURL: 'http://dsq.ljc.icu:8083/', //云登录
  // baseURL: 'http://dsq.ljc.icu:8080/', //云后台数据

  // mock地址
  // baseURL: 'http://127.0.0.1:5000/',
  // 设置超时时间（10s）
  timeout: 10000,
  // 跨域时候允许携带凭证
  // withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
  },
};

class RequestHttp {
  service: AxiosInstance;
  public constructor(config: AxiosRequestConfig) {
    // 实例化axios
    this.service = axios.create(config);
    this.service.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        let token = sessionStorage.getItem('token');
        return {
          ...config,
          headers: { ...config.headers, token: token },
        };
      },
      (error: AxiosError) => {
        return Promise.reject(error);
      }
    );

    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data } = response;
        // if (data.code !== 200) {
        //   return Promise.reject(data);
        // }
        if (data.data?.token) {
          sessionStorage.setItem('token', data.data.token);
        }
        return data;
      },
      async (error: AxiosError) => {
        return Promise.reject(error);
      }
    );
  }

  // * 常用请求方法封装
  get<T>(
    url: string,
    params?: any,
    _object = {}
  ): Promise<Axios.ResultData<T>> {
    return this.service.get(url, { params, ..._object });
  }
  post<T>(
    url: string,
    params?: any,
    _object = {}
  ): Promise<Axios.ResultData<T>> {
    return this.service.post(url, params, _object);
  }
}

export default new RequestHttp(config);
